package com.eliza.v.server.tcp

import io.vertx.core.AbstractVerticle
import io.vertx.core.AsyncResult
import io.vertx.core.Vertx
import io.vertx.core.buffer.Buffer
import io.vertx.core.net.NetSocket

class VertxTCPClient : AbstractVerticle() {
    override fun start() {
        // 创建一个TCP客户端
        val client = vertx.createNetClient()

        // 连接服务器
        client.connect(33323, "localhost") { conn: AsyncResult<NetSocket?> ->
            if (conn.succeeded()) {
                println("客户端连接服务端成功")
                netSocket = conn.result()
                // 向服务器写数据
                netSocket!!.write(Buffer.buffer("Hello Vertx from Client!"))

                // 读取服务器的响应数据
                netSocket!!.handler { buffer: Buffer ->
                    println(
                        "接收到的数据为：$buffer"
                    )
                }
            } else {
                println("连接服务器异常")
            }
        }
    }

    companion object {
        private var netSocket: NetSocket? = null
        @JvmStatic
        fun main(args: Array<String>) {
            Vertx.vertx().deployVerticle(VertxTCPClient())
        }
    }
}